<?php
# gearman client class
class GMC extends GearmanClient{

	protected $job_name;

	/**
	* inherit class GearmanClient '__contruct' 
	* @param string|array $servers e.g. '127.0.0.1:4730' or array('127.0.0.1:4730','192.168.1.34:4730')
	* @return void
	*/	
	function __construct($servers = '') {
		parent::__construct();

		try {
			$this->gmc_connect($servers);
		} catch (Exception $e) {
			echo 'GMC Connect Error: ' . $e->getMessage() . "\n";
		}

	}


	private function gmc_connect($servers) {
		
		global $site_global_config;
		$servers = $site_global_config['GEARMAN_SERVERS'];
		
		if(empty($servers)) {
			$this->addServer();
		} else {
			$this->addServers($servers);
		}
	}


	/**
	*  
	* @param array $param_h
	*	integer $param_h['from']
	*	integer $param_h['to']
	*	integer $param_h['type']
	*	string $param_h['message']
	*	integer $param_h['canned_message']
	* @return bool|custom: job_status
	*/	
	function job_do($job_name, $param_h=array(), $doBackground=true) {
		
		$this->job_name = $job_name;
		
		if(!empty($this->job_name) && is_array($param_h)) {
			$param_h = json_encode($param_h);
			if ($doBackground === true) {
				return $this->doBackground($this->job_name, $param_h);
			} else {
				return $this->do($this->job_name, $param_h);
			}
		} else {
			return false;
		}
	}


	protected function get_job_status() {
		list($numerator, $denominator)= $this->doStatus();
		echo "Status: $numerator/$denominator complete\n";
	}

	protected function m_addTask($param_a, $context=null) {

		$unique_hash = $this->job_name . '_' . md5(microtime());
		$unique_id = 0;
		foreach ($param_a as $param_h) {
			parent::addTask($this->job_name, $param_h, $context, $unique_hash . '_' . (++$unique_id));
		}
	}

	/*
	function addTask($param_h, $context=null) {
		$unique_hash_id = $this->job_name . '_' . md5(microtime()) . '_1';
		parent::addTask($this->job_name, json_encode($param_h), $context, $unique_hash_id);
	}

	function addTaskBackground($param_h, $context=null) {
		$unique_hash_id = $this->job_name . '_' . md5(microtime()) . '_1';
		parent::addTaskBackground($this->job_name, json_encode($param_h), $context, $unique_hash_id);
	}
	*/

} //end class;

/*
function complete($task) 
{ 
  print "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n"; 
}
*/

?>